package com.eportal.service.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.domain.Sysopt;
import com.eportal.domain.UsersCommunity;
import com.eportal.domain.UsersEnjoy;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.service.UsersCommunityService;
import com.eportal.service.UsersEnjoyService;
import com.framework.jqgrid.JqGridPager;

@Service("UsersEnjoyService")
public class UsersEnjoyServiceImpl  implements UsersEnjoyService{
	
	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(UsersEnjoyServiceImpl.class.getName());
	
	@Resource(name="dao")
	private BaseDAO dao;
	@Autowired
	private UsersCommunityService usersCommunityService;
	 
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }

	@Override
	public UsersEnjoy get(Long sid){
		UsersEnjoy UsersEnjoy = (UsersEnjoy)dao.getById(UsersEnjoy.class, sid);
		return UsersEnjoy;
	}
	
	public UsersEnjoy getByWhere(String where){ StringBuffer sb = new StringBuffer("from UsersEnjoy ");
		sb.append(where);
		return (UsersEnjoy) dao.loadObject(sb.toString());
	}
	
	public List<Map<String, Object>> list(String sql) {
		return dao.queryBySql(sql);
	}
	
	@Override
	public void delete(Long id) {
		UsersEnjoy usersEnjoy = (UsersEnjoy) dao.getById(UsersEnjoy.class, id);
        dao.delete(usersEnjoy);
	}
	@Override
	public void update(UsersEnjoy usersEnjoy) throws Exception {
        dao.update(usersEnjoy);
	}
	
	@Override
	public void delete(List<Long> ids) {
		 for (Long id : ids) {
	            delete(id);
	     }
	}


	/**
     * 删除
     */
    @LogAnnotation(operateDescribe="乐享删除")  
    public Map<String, Object> deleteMethod(String sid){
    	 try {
    		 result.put("objectId", sid);
             delete(Long.parseLong(sid));
             result.put("code", 1);
             result.put("msg", "操作成功");
         } catch (Exception e) {
             log.error("乐享删除失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
    	 return result;
    }

	
	@Override
	@LogAnnotation(operateDescribe="乐享置顶或取消置顶操作")  
	public Map<String, Object> enjoyTopMethod(String userid, String communityid, String status) {
		result.put("objectId", userid);
        try {
       	 if (StringUtils.isBlank(status)) {
       		 result.put("code", 0);
                result.put("msg", "无法判断操作行为");
                return result;
       	 }
       	 
       	StringBuffer sb = new StringBuffer(" status=1 and communityId ='");
		sb.append(communityid);
		sb.append("'");
		sb.append(" and userId='");
		sb.append(userid);
		sb.append("'");
       	UsersCommunity usersCommunity = usersCommunityService.getByWhere(sb.toString());
        if (usersCommunity == null) {
        	 result.put("code", 0);
             result.put("msg", "置顶或取消置顶操作失败");
             return result;
        }
       	if ("0".equals(status)) {
       		if(!canTop(usersCommunity.getCommunityId())){
   			 result.put("code", 0);
             result.put("msg", "置顶失败，一个小区只能置顶五个");
             return result;
   		 }
       		usersCommunity.setEnjoyOrder(System.currentTimeMillis());
		}else{
			usersCommunity.setEnjoyOrder(0L);
		}
       	usersCommunityService.update(usersCommunity);
            result.put("code", 1);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("乐享更新失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
        }
        return result;
	}


	private boolean canTop(String communityId) {
		String hql  = "select count(uc.sid) from UsersCommunity uc "
				+ "where uc.enjoyOrder>0 and uc.status=1 and uc.communityId='"+communityId+"'";
		int count = dao.countQuery(hql);
		if (count<5) {
			return true;
		}
		return false;
	}
	@Override
	public Map<String, Object> UsersEnjoyList(String userId) {
		try {
			result = new HashMap<String, Object>();
			//乐享图片
			StringBuffer sb = new StringBuffer(""
					+ "select t.sid,t.userid,t.communityid,t.pic ,TO_CHAR (t.cTime,'yyyy-mm-dd HH24:mi:ss') as cTime,nvl(uc.enjoy_order,0) as enjoyOrder "
					+ "from t04_users_enjoy t "
					+ "left join t04_users_community uc on t.userid=uc.userid and t.communityid= uc.communityid "
					+ "left join t03_community c on uc.communityid=c.sid "
					+ " where t.userid='");
			sb.append(userId);
			sb.append("'");
			
			Sysopt  user= (Sysopt)getSession().getAttribute("user");
			int userRole =  (Integer) getSession().getAttribute("userRole");
			if (userRole == 3 || userRole == 4) {
				sb.append(" and c.agtCode ='");
				sb.append(user.getAgtCode());
				sb.append("'");
			}else if (userRole == 5 || userRole == 6) {
				sb.append(" and uc.status=1 and  uc.communityId ='");
				sb.append(user.getCommunityId());
				sb.append("'");
			}
			sb.append(" order by t.cTime desc");
			List<Map<String, Object>> list = dao.queryBySql(sb.toString());
			if (list.size() ==0) {
				result.put("picNum", 0);
				result.put("CTIME", "未知");
				result.put("rownu",0);
				result.put("code", 1);
				return result;
			}else {
				result=  list.get(0);
				result.put("code", 1);
				int picNumber = 0;
				for (Map<String, Object> map : list) {
					if (StringUtils.isBlank((String) map.get("pic"))) continue;
					else{
						String[] str = map.get("pic").toString().split(",");
						picNumber +=str.length;
					}
				}
				result.put("picNum", picNumber);
				result.put("CTIME", list.get(0).get("cTime").toString());
				if (list.size()>1) {
					result.put("rownu", "hidden");
				}else{
					List<Map<String, Object>> list1 = queryRownuScore(list.get(0).get("communityid").toString(),userId);
					if (list1.size() >0) {
						result.put("rownu", list1.get(0).get("rownu"));
					}else{
						result.put("rownu", 0);
					}
				}
			}
			
		} catch (Exception e) {
			result.put("code", 0);
            result.put("msg", "查询失败");
            log.error(this, e);
		}
		return result;
	}

	public List<Map<String, Object>> queryRownuScore(String communityid, String userId) {
		
		StringBuffer sb = new StringBuffer(""
				+ "select u.rownu,u.sid,u.userid,u.score "
				+ "from "
				+ "(select row_number() over (order by t.score desc,t.sid asc) as rownu ,t.userid,t.sid,t.score from t04_users_community t "
				+ "where t.communityid='");
		sb.append(communityid);
		sb.append("' order by t.score desc,t.sid asc"
				+ ")u "
				+ "where u.userid='");
		sb.append(userId);
		sb.append("'");
		return dao.queryBySql(sb.toString());
	}

	@Override
	@LogAnnotation(operateDescribe="乐享清空")  
	public Map<String, Object> cleanEnjoyMethod (String userid) throws Exception{
		try {
			result = new HashMap<String, Object>();
			Sysopt  user= (Sysopt)getSession().getAttribute("user");
			int userRole =  (Integer) getSession().getAttribute("userRole");
			
			StringBuffer sb = new StringBuffer();
			sb.append("select t.sid from t04_users_enjoy  t left join t03_community  c on t.communityId=c.sid "
					+ "where ");
			if (userRole == 1 || userRole == 2) {
				sb.append("t.userId ='");
				sb.append(userid);
				sb.append("'");
			}else if (userRole == 3 || userRole == 4) {
				sb.append("t.userId ='");
				sb.append(userid);
				sb.append("'");
				sb.append(" and c.agtCode ='");
				sb.append(user.getAgtCode());
				sb.append("'");
			}else if (userRole == 5 || userRole == 6) {
				sb.append("t.userId ='");
				sb.append(userid);
				sb.append("'");
				sb.append(" and  t.communityId ='");
				sb.append(user.getCommunityId());
				sb.append("'");
			}
			List<Map<String, Object>> list = list(sb.toString());
			
			if (list.size()<1) {
				result.put("code", 0);
	            result.put("msg", "乐享查询为空");
	            return result;
			}
			UsersEnjoy usersEnjoy;
			for (Map<String, Object> map : list) {
				usersEnjoy = get(Long.parseLong(map.get("sid").toString()));
				usersEnjoy.setaUserName(Long.toString(user.getSid()));
				usersEnjoy.setaTime(new Timestamp(System.currentTimeMillis()));
				usersEnjoy.setContent("");
				usersEnjoy.setPic("");
				update(usersEnjoy);
			}
			result.put("code", 1);
            result.put("msg", "乐享清空成功");
		} catch (Exception e) {
			result.put("code", 0);
            result.put("msg", "乐享清空失败");
            log.error(this, e);
			throw new MdKnownRunTimeException("乐享清空失败");
		}
		return result;
	}

	



}
